<template>
  <div class="navbar">
    <div class="left-side">
      <a-space>
        <img
          alt="logo"
          src="../../assets/images/logo2.png"
          style="width: 180px"
        />
        <!-- <a-typography-title
          :style="{ margin: 0, fontSize: '18px' }"
          :heading="5"
        >
          Mes 3.0
        </a-typography-title> -->
        <!-- <icon-menu-fold
          v-if="appStore.device === 'mobile'"
          style="font-size: 22px; cursor: pointer"
          @click="toggleDrawerMenu"
        /> -->
      </a-space>
    </div>

    <div class="menu-demo" v-if="role === 'admin'">
      <div class="bg1" />
      <div class="bg2" />
      <div class="bg3" />
      <!-- <a-menu
        mode="horizontal"
        :default-selected-keys="[currMenusKey]"
        @menu-item-click="itemClick"
      >
        <a-menu-item
          ref="menusRef"
          class="menu-item"
          v-for="item in managementMenus"
          :key="item.key"
        >
          {{ item.name }}
        </a-menu-item>
      </a-menu> -->
      <template v-for="item in managementMenus" :key="item.key">
        <div
          v-if="item.key !== '11'"
          :class="[
            'head-menu-item',
            [item.key === currMenusKey ? 'selected' : '']
          ]"
          @click="itemClick(item.key)"
        >
          {{ item.name }}
        </div>
      </template>
    </div>
    <a-space>
      <a-input
        :style="{ width: '300px', borderRadius: '20px', zIndex: 999 }"
        placeholder="搜索员工、功能、部门、岗位、帮助文档"
        allow-clear
      />
    </a-space>
    <ul class="right-side" @click="aa">
      <!-- <li data-index="2">
        <a-tooltip content="搜索">
          <a-button class="nav-btn" type="outline" :shape="'circle'">
            <template #icon>
              <icon-search />
            </template>
          </a-button>
        </a-tooltip>
      </li>
      <li data-index="1">
        <a-tooltip content="二维码">
          <a-button class="nav-btn" type="outline" :shape="'circle'">
            <template #icon>
              <icon-font type="icon-erweima"></icon-font>
            </template>
          </a-button>
        </a-tooltip>
      </li> -->
      <li>
        <a-tooltip
          content="通知"
          @click="router.push({ name: 'InformationCenter' })"
        >
          <a-badge :count="noticeStore.MessagTotal">
            <a-button
              class="nav-btn"
              type="outline"
              :shape="'circle'"
              @click="setPopoverVisible"
            >
              <icon-notification />
            </a-button> </a-badge
        ></a-tooltip>
      </li>
      <li>
        <a-tooltip content="设置">
          <a-button
            class="nav-btn"
            type="outline"
            :shape="'circle'"
            @click="setVisible"
          >
            <template #icon>
              <icon-settings />
            </template>
          </a-button>
        </a-tooltip>
      </li>
      <li>
        <a-dropdown trigger="click">
          <a-avatar :size="32" class="nav-btn">
            <img :src="avatar" />
          </a-avatar>
          <template #content>
            <a-doption>
              <a-space @click="router.push({ name: 'UserSetting' })">
                <icon-user />
                <span> 个人设置 </span>
              </a-space>
            </a-doption>
            <a-doption>
              <a-space @click="switchRoles">
                <icon-tag />
                <span> 切换角色 </span>
              </a-space>
            </a-doption>
            <!-- <a-doption>
              <a-space @click="$router.push({ name: 'Info' })">
                <icon-user />
                <span>
                  {{ 'messageBox.userCenter' }}
                </span>
              </a-space>
            </a-doption>
            <a-doption>
              <a-space @click="$router.push({ name: 'Setting' })">
                <icon-settings />
                <span>
                  {{ 'messageBox.userSettings' }}
                </span>
              </a-space>
            </a-doption> -->
            <a-doption>
              <a-space @click="handleLogout">
                <icon-export />
                <span> 退出 </span>
              </a-space>
            </a-doption>
          </template>
        </a-dropdown>
      </li>
    </ul>
  </div>
  <Setting ref="settingModele" />
</template>

<script lang="tsx" setup>
import Setting from './components/Setting.vue';
import { useRouter } from 'vue-router';
import { computed, ref, inject, reactive, nextTick, watchEffect } from 'vue';
import style from './style.module.less';
import VueQr from 'vue-qr/src/packages/vue-qr.vue';
// import { useDark, useToggle, useFullscreen } from '@vueuse/core';
import {
  useAppStore,
  useUserStore,
  useMenusStore,
  useTabBarStore
} from '@/store';
import IconFont from '@/components/IconFont/index.vue';
// import { LOCALE_OPTIONS } from '@/locale';
import usePermission from '@/hooks/permission';
// import useLocale from '@/hooks/locale';
import useUser from '@/hooks/user';
import { useNoticeStore } from '@/store/index';
// import MessageBox from '../message-box/index.vue';
import { PostApplySign } from '@/apis/management/personnel/changeManagement/inductionManagement';
import { NavbarMenus } from './type';
import {
  Modal,
  Tooltip,
  TableColumn,
  Popconfirm,
  Input,
  Button,
  Message,
  Space,
  Radio,
  RadioGroup,
  InputNumber
} from '@arco-design/web-vue';

type TSettingModal = InstanceType<typeof Setting>;
const { headPortrait } = JSON.parse(localStorage.getItem('userInfo') + '');
const personalHeadPortraitold = localStorage.getItem('headPortrait');

const noticeStore = useNoticeStore();
const router = useRouter();
const appStore = useAppStore();
const userStore = useUserStore();
const tabBarStore = useTabBarStore();
const menusStore = useMenusStore();
const { logout } = useUser();
const settingModele = ref<TSettingModal>();
// const { changeLocale } = useLocale();
// const { isFullscreen, toggle: toggleFullScreen } = useFullscreen();
// const locales = [...LOCALE_OPTIONS];
const avatar = computed(() => {
  return userStore.headPortrait || headPortrait || personalHeadPortraitold;
});

const getMessagTotal = async () => {
  await noticeStore.getMessagTotal();
  console.log();
};
getMessagTotal();
const role = computed(() => {
  if (userStore.role !== '') return userStore.role;
  return localStorage.getItem('userRole');
});

// 记录当前头部菜单的key
let currMenusKey = computed(
  () => menusStore.currentKey || sessionStorage.getItem('currentMenuKey')
);

const managementMenus = reactive<NavbarMenus[]>([
  // {
  //   name: '首页',
  //   key: '1',
  //   // icon: 'icon-home',
  //   path: 'home'
  // },
  {
    name: '组织',
    key: '2',
    // icon: 'icon-file',
    path: 'organization'
  },
  {
    name: '人事',
    key: '3',
    // icon: 'icon-select-all',
    path: 'human'
  },
  {
    name: '考勤',
    key: '4',
    // icon: 'icon-select-all',
    path: 'attendance'
  },
  {
    name: '绩效',
    key: '5',
    icon: 'icon-bookmark',
    path: 'performance'
  },
  {
    name: '薪酬',
    key: '6',
    icon: 'icon-bookmark',
    path: 'salary'
  },
  {
    name: '合同',
    key: '7',
    icon: 'icon-relation',
    path: 'contract'
  },
  {
    name: '行政',
    key: '8',
    icon: 'icon-relation',
    path: 'administration'
  },
  {
    name: '审批',
    key: '10',
    icon: 'icon-bookmark',
    path: 'approval'
  },
  {
    name: '设置',
    key: '11',
    icon: 'icon-bookmark',
    path: 'setting'
  }
]);

// 点击头部导航菜单，获取对应的侧边栏菜单
const itemClick = (key: string) => {
  let currPath = ref(); // 获取当前menus的path，根据path在pinia里面进行侧边路由菜单的获取
  managementMenus.forEach((item) => {
    if (item.key === key) currPath.value = item.path;
  });
  // 根据key来判断，点击头部导航栏默认跳到第一个菜单
  switch (key) {
    case '1':
      router.push({
        path: '/home/workplace'
      });
      break;
    case '2':
      router.push({
        name: 'OmStructure'
      });
      break;
    case '3':
      router.push({
        name: 'HumanRoster'
      });
      break;
    case '4':
      router.push({
        name: 'AttendanceBaseSetting'
      });
      break;
    case '5':
      router.push({
        name: 'PerformanceBaseSetting'
      });
      break;
    case '6':
      router.push({
        name: 'SalaryBaseSetting'
      });
      break;
    case '7':
      router.push({
        name: 'ContractBaseSetting'
      });
      break;
    case '8':
      router.push({
        name: 'EnterpriseAnnouncement'
      });
      break;
    case '10':
      router.push({
        name: 'ApprovalList'
      });
      break;
    case '11':
      router.push({
        name: 'Setting'
      });
      break;

    // case '5':
    //   router.push({
    //     name: 'Performance'
    //   });
    //   break;
    default:
      break;
  }
  menusStore.setMenuKey(key);
  menusStore.setCurrMenus(currPath.value);
};

const generateQRCode = async () => {
  try {
    const { sign, timeStamp } = await PostApplySign({
      duration: -1 // 一开始点击链接默认永久传-1
    });

    let currRadio = ref(1), // 储存当前选中的有效期
      isDisabled = ref(true), // 储存当前是否是永久有效期
      duration = ref(undefined); // 储存当前有效期
    const radioChange = (val: number) => {
      duration.value = undefined;
      isDisabled.value = val === 2 ? false : true;
      currRadio.value = val;
    };

    let text = ref(
      `http://192.168.0.20:5173/human/changeManagement/inductionManagement/addNewemployee?sign=${sign}&timeStamp=${timeStamp}`
    );
    const QrCode = () => {
      return (
        <VueQr
          ref="qrCode"
          text={text.value}
          logoScale={40}
          size={190}
          margin={10}
        />
      );
    };

    // 刷新链接
    const refreshLink = async () => {
      const res = await PostApplySign({
        duration: currRadio.value === 1 ? -1 : duration.value
      });
      text.value = `http://192.168.0.20:5173/human/changeManagement/inductionManagement/addNewemployee?sign=${res.sign}&timeStamp=${res.timeStamp}`;
    };

    // 复制链接
    const copyLink = () => {
      navigator.clipboard.writeText(text.value).then(
        function () {
          /* 如果文本成功复制，显示一条消息来确认 */
          Message.success('复制成功！');
        },
        function (err) {
          /* 如果出现错误，显示一条错误消息 */
          Message.error('复制失败，请重试！');
        }
      );
    };

    const content = (
      <div className={style.qrCodeBox}>
        <div className={style.qrCode}>
          <QrCode />
          <div>微信扫描二维码查看</div>
        </div>
        <section>
          <Space size={0}>
            <h3>有效类型：</h3>
            <RadioGroup
              v-model={currRadio.value}
              onChange={radioChange}
              precision={1}
            >
              <Radio value={1}>永久</Radio>
              <Radio value={2}>有效期</Radio>
            </RadioGroup>
            <InputNumber
              placeholder="请输入有效天数"
              min={1}
              hide-button
              disabled={isDisabled.value}
              v-model={duration.value}
              precision={0}
            ></InputNumber>
          </Space>
          <Space>
            <h3>入职邀请链接：</h3>
            <div>
              <Button
                type="text"
                v-slots={{
                  icon: () => <IconFont type="icon-shuaxin"></IconFont>,
                  default: () => '点击刷新链接'
                }}
                onClick={refreshLink}
                v-show={currRadio.value !== 1}
              ></Button>
            </div>
          </Space>
          <div>分享邀请链接给入职者，入职者可点击链接快速填写入职申请信息</div>
          <div
            style={{
              display: 'flex'
            }}
          >
            <Input disabled v-model={text.value}></Input>
            <Button type="primary" onClick={copyLink}>
              复制链接
            </Button>
          </div>
        </section>
      </div>
    );
    Modal.open({
      title: '二维码',
      width: '60%',
      content,
      okText: '下载二维码',
      cancelText: '关闭',
      maskClosable: false
    });
  } catch (error: unknown) {
    console.log(error);
  }
};

const aa = (e) => {
  const liElement = e.target.closest('li');
  console.log('====================================');
  console.dir(liElement);
  console.log('====================================');
  if (liElement) {
    const dataIndex = liElement.getAttribute('data-index');

    switch (dataIndex) {
      // 二维码
      case '1':
        generateQRCode();
        break;
      default:
        break;
    }
  }
};

// const theme = computed(() => {
//   return appStore.theme;
// });
// const isDark = useDark({
//   selector: 'body',
//   attribute: 'arco-theme',
//   valueDark: 'dark',
//   valueLight: 'light',
//   storageKey: 'arco-theme',
//   onChanged(dark: boolean) {
//     // overridden default behavior
//     appStore.toggleTheme(dark);
//   },
// });
// const toggleTheme = useToggle(isDark);
// const handleToggleTheme = () => {
//   toggleTheme();
// };
const setVisible = () => {
  //   appStore.updateSettings({ globalSettings: true });
  // };
  // const refBtn = ref();
  // const triggerBtn = ref();
  // const setPopoverVisible = () => {
  //   const event = new MouseEvent('click', {
  //     view: window,
  //     bubbles: true,
  //     cancelable: true,
  //   });
  //   refBtn.value.dispatchEvent(event);
  // console.log('SettingModal.value', settingModele.value);
  itemClick('11');
  // settingModele.value?.handleClick();
};
const handleLogout = () => {
  logout();
};
// const setDropDownVisible = () => {
//   const event = new MouseEvent('click', {
//     view: window,
//     bubbles: true,
//     cancelable: true,
//   });
//   triggerBtn.value.dispatchEvent(event);
// };
const switchRoles = async () => {
  const res = await userStore.switchRoles();
  Message.success(res as string);
  localStorage.setItem('userRole', res as string);

  /*
    如果是管理员跳到管理员工作台，
    否则跳到员工端工作台
  */
  if (res === 'admin') {
    router.push({
      name: 'WorkPlace'
    });
    menusStore.setCurrMenus('home'); // 赋值，用来刷新路由
    tabBarStore.resetTabList();
  } else {
    router.push({
      name: 'C_ClientWorkPlace'
    });
    menusStore.setCurrMenus('');
    tabBarStore.resetTabList();
    console.log('====================================aaa');
    console.log(tabBarStore.getTabList);
    console.log('====================================');
  }
};
// const toggleDrawerMenu = inject('toggleDrawerMenu') as () => void;
</script>

<style scoped lang="less">
.head-menu-item {
  color: #fff;
  padding: 0 10px;
  margin: 0 10px;
  cursor: pointer;
  height: 30px;
  border-radius: 2px;
  z-index: 999;
  white-space: nowrap;
  display: flex;
  align-items: center;
  &:hover {
    background: #fff;
    color: #2971d6;
  }
}
.selected {
  background: #fff;
  color: #2971d6;
}
:deep(.arco-menu-light) {
  background-color: rgba(255, 255, 255, 0);
}
:deep(.arco-menu-inner) {
  // background-color: #0057f9; //rgb(var(--primary-4));
  background: rgba(255, 255, 255, 0) !important;
}
:deep(.arco-menu-horizontal) {
  background: rgba(255, 255, 255, 0) !important;
}
:deep(.arco-menu-item) {
  background: none;
  color: #fff !important;
  height: 30px;
  &:hover {
    // background: none;
    color: rgb(0, 0, 0) !important;
  }
}
:deep(.arco-menu-selected) {
  // background-color: #fff !important;
  color: #fff !important;
  font-weight: 700 !important;
  .arco-icon {
    color: #fff !important;
  }
  &:hover {
    color: #000 !important;
    .arco-icon {
      color: #000 !important;
    }
  }
}
:deep(.arco-menu-selected-label) {
  background-color: #fff !important;
  .arco-icon {
    color: #fff !important;
  }
}
:deep(.arco-menu-pop-header) {
  background: none !important;
  color: #fff !important;
}

:deep(.arco-menu-overflow-sub-menu) {
  .arco-icon {
    color: #fff !important;
  }
}

.navbar {
  display: flex;
  justify-content: space-between;
  height: 100%;
  background-color: #0057f9; //rgb(var(--primary-4));
  // border-bottom: 1px solid var(--color-border);
}

.arco-icon {
  font-size: 20;
}

.left-side {
  display: flex;
  align-items: center;
  padding-left: 20px;
}

.menu-demo {
  display: flex;
  align-items: center;
  font-weight: 700;
  box-sizing: border-box;
  width: 100%;
  position: relative;
  padding: 0 10px;
  // left: 100px;
  // padding: 40px;
  // display: flex;
  // text-align: center;
  .bg1 {
    position: absolute;
    left: 10px;
    height: 100%;
    width: 150px;
    transform: skew(-35deg);
    background: rgb(215, 215, 215);
    // z-index: 999;
    opacity: 0.3;
  }
  .bg2 {
    position: absolute;
    left: 600px;
    top: -60px;
    width: 0;
    height: 0;
    border-style: solid;
    border-width: 60px;
    border-color: transparent transparent rgba(215, 215, 215, 0.3) transparent;
  }
  .bg3 {
    position: absolute;
    left: 650px;
    top: -40px;
    width: 0px;
    height: 0px;
    border-style: solid;
    border-width: 50px;
    border-color: transparent transparent rgba(215, 215, 215, 0.3) transparent;
  }
}

.right-side {
  display: flex;
  padding-right: 20px;
  list-style: none;

  :deep(.locale-select) {
    border-radius: 20px;
  }

  li {
    display: flex;
    align-items: center;
    padding: 0 10px;
  }

  a {
    color: var(--color-text-1);
    text-decoration: none;
  }

  .nav-btn {
    border-color: rgb(var(--gray-2));
    color: #000; //rgb(var(--gray-8));
    background: #fff;
    font-size: 16px;
    cursor: pointer;
    &:hover {
      background: #eee;
    }
  }

  .trigger-btn,
  .ref-btn {
    position: absolute;
    bottom: 14px;
  }

  .trigger-btn {
    margin-left: 14px;
  }
}
</style>

<style lang="less">
.message-popover {
  .arco-popover-content {
    margin-top: 0;
  }
}
</style>
